#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <memory.h>
#include "ts.h"

void usage(char *argv[])
{
    printf("Usage:\n%s [ts file]\n", argv[0]);
}

int main(int argc, char *argv[])
{
    ts_t *ts = 0;
    int i_file, ok, packet;
    int hour, minute, sec, ssec, msec;
    FILE *o_file;
    long if_len, n_ts_p;
    unsigned char *buf = 0;
    if (argc != 2)
        usage(argv);
    buf = new unsigned char(188);
    ts = new ts_t;
    if (!buf)
        return -1;
    i_file = open(argv[1], O_RDONLY);
    struct stat sb;
    fstat(i_file, &sb);
    if_len = sb.st_size;
    n_ts_p = if_len / 188;
    ok = 0;
    for (int i = 0; i < n_ts_p; i++) {
        lseek(i_file, i*188, SEEK_SET);
        read(i_file, buf, 188);
        ts_parse(buf, ts);
        if (ts->IDR)
            ok |= 0x1;
        if (ts->SPS)
            ok |= 0x2;
        if (ts->PPS)
            ok |= 0x4;
        if ((ts->pusi) && (ts->pes.PDflags) && (ts->pes.stream_id == 0xe0)) {
            if (ok==7) {
                printf("Packet No.%d\t: PTS: %02d:%02d:%02d:%02d\n", packet, hour, minute, sec, ssec);
                ok = 0;
            }
            msec = ts->pes.pts / 90;
            hour = (msec / 1000 / 3600) % 60;
            minute = ((msec / 1000) % 3600) / 60;
            sec = (msec / 1000) % 60;
            ssec = (msec % 1000) * 60 / 1000;
            packet = i;
        }
    }
    close(i_file);
}
